﻿var ViewModel = function () {
    var self = this;
    self.books = ko.observableArray();
    self.error = ko.observable();

    var booksUri = "/api/books/";
    function ajaxHelper(uri, method, data) {
        self.error('');
        return $.ajax({
            type: method,
            url: uri,
            dataType: 'json',
            contentType: 'application/json',
            data: data ? JSON.stringify(data) : null
        }).fail(function (jqXHR, textStatus, errorThrown) {
            self.error(errorThrown)
        });
    }
    function getAllBooks() {
        ajaxHelper(booksUri, 'GET').done(function (data) {
            self.books(data);      
        });
    }

    getAllBooks();

    self.detail = ko.observable();
    self.getBookDetail = function (item) {
        ajaxHelper(booksUri + item.Id, 'GET').done(function (data) {
            self.detail(data);
           
        });
    }

    self.authors = ko.observableArray();
    self.newBook = {
        Author: ko.observable(),
        Genre: ko.observable(),
        Price: ko.observable(),
        Title: ko.observable(),
        Year: ko.observable()
    }
    var authorsUri = '/api/authors/';

    function getAuthors() {
        ajaxHelper(authorsUri, 'GET').done(function (data) {
            self.authors(data);
        });
    }
    getAuthors();

    self.addBook = function (formElement) {
        var book = {
            AuthorId: self.newBook.Author().Id,
            Genre: self.newBook.Genre(),
            Price: self.newBook.Price(),
            Title: self.newBook.Title(),
            Year: self.newBook.Year()
        };
        ajaxHelper(booksUri, 'POST', book).done(function (item) {
            self.books.push(item);
        });
    }

    self.delete = ko.observable();
    self.deleteBook = function (item) {
        ajaxHelper(booksUri + item.Id, 'DELETE').done(function () {
            self.delete(item);
            getAllBooks();
        });
    };

};
ko.applyBindings(new ViewModel);

function Remove(_element) {
    var id = _element.getAttribute("tip");
    var _parenttdElement = _element.parentNode;
    var _parenttrElement = _parenttdElement.parentNode;
    var _parenttbElement = _parenttrElement.parentNode;
    for (var i = 0; i < uploader.files.length; i++) {
        if (uploader.files[i].id == id) {
            uploader.removeFile(uploader.files[i]);
            if (_parenttbElement) {
                _parenttbElement.removeChild(_parenttrElement);
            }
            break;
        }
    }
}

var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'pickfiles', // you can pass in id...
    container: document.getElementById('btncontainer'), // ... or DOM Element itself
    url: 'api/upload',
    flash_swf_url: '../Scripts/plupload/Moxie.swf',
    silverlight_xap_url: '../Scripts/plupload/Moxie.xap',
    filters: {
        max_file_size: '100mb',
        mime_types: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions: "zip" },
            { title: "DLL files", extensions: "dll" }
        ],
        prevent_duplicates: true
    },
    init: {
        PostInit: function () {
            document.getElementById('filelist').innerHTML = '';
            document.getElementById('uploadfiles').onclick = function () {
                uploader.start();
                return false;
            };
        },
        FilesAdded: function (up, files) {
            plupload.each(files, function (file) {
                document.getElementById('filelist').innerHTML += '<tr><td><div style="cursor:coress" >' + file.name + '<b></b></div></td><td>' + plupload.formatSize(file.size) + '</td><td id="' + file.id + '"><b></b></td><td><span style="cursor:pointer" class="glyphicon glyphicon-remove" onclick="Remove(this);" tip="' + file.id + '"></span></td></tr></tr>';
            });
        },
        UploadProgress: function (up, file) {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
        },
        Error: function (up, err) {
        },
        FilesRemoved: function (up, file) {
        },
        UploadComplete: function (up, files) {
            GetimgList();
            $('#myModal').modal('hide');
            $("#filelist").empty();
        }
    }
});
uploader.init();